<template>
  <div>
    <div class="main-head has-radios flex-between container-fluid">
      <div class="title">
        <h1 v-text="$t('pro.transactionRecord.title')"></h1>
      </div>
      <a-radio-group v-model="rdChecked" buttonStyle="solid" @change="handleCheckedChange">
        <a-spin :spinning="spinningDate" class="dsp-spin">
          <a-radio-button
                  v-for="(value,key) in radios"
                  :key="key"
                  :value="value[0]"
          >{{value[1]}}</a-radio-button>
        </a-spin>
      </a-radio-group>
    </div>
    <div class="content container-fluid">
      <div class="portlet">
        <div class="tools flex-between">
          <div class="tools-l grid">
            <a-select style="min-width: 200px;" v-model="transactionType" @change="searchTransactions">
              <a-select-option v-for="item in transactionTypes" :key="item.key">{{ item.value }}</a-select-option>
            </a-select>
          </div>


          <div class="tools-r grid">
            <a-range-picker
                style="width: 385px;"
                :format="dateFormat"
                @change="handleDatePickerChange"
                showToday
                v-show="this.rdChecked == 'getCustom'"
                @openChange="openChange"
            />
          </div>
        </div>

        <div>
          <!-- table列表 and 分页 -->
          <div v-if="!!dataList && dataList.length > 0" class="bottom-table-page">
            <!-- 表格数据 -->
            <a-table
                  :columns="columns"
                  :rowKey="record => record.id"
                  :dataSource="dataList"
                  :loading="listLoading"
                  :pagination="false"
                  :scroll="{ x: 1000 }"
            >
              <template slot="sta" slot-scope="sta">
                {{ status[sta || 2].value }}
              </template>

              <template slot="type" slot-scope="type, text">
                {{ getTransactionIDMethods.find(item => item.key == type).value || ' - ' }}
                <a href="javascript:;" @click="handleDownload($event,text)">
                  <a-icon  type="download" style="font-size: 1.5rem"/>
                </a>
              </template>

              <template slot="createdAt" slot-scope="createdAt">
                {{ createdAt | formatLentime }}
              </template>

            </a-table>
            <!-- 分页 -->
            <div class="public-page-box">
              <a-pagination
                  showSizeChanger
                  showQuickJumper
                  :pageSize.sync="pagination.pageSize"
                  :total="pagination.total"
                  v-model="pagination.current"
                  @change="onShowSizeChange"
                  @showSizeChange="onShowSizeChange"
              />
            </div>
          </div>

          <div v-else>
            <a-empty
                    image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
              <span slot="description">{{$t('pro.campaigns.activeNotMess')}}</span>
            </a-empty>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getRecharge, getInvoice } from '../../api/user'
import { formatLentime } from '../../filters'
import { download2 } from "../../utils/downLoad";
export default {
  data() {
    return {
      dateFormat: "YYYY-MM-DD",
      transactionType: -1,
      empty: false, //是否有数据显示表格

      pagination: {
          pageSizeOptions: ['10', '20', '30', '40', '50'],
          current: 1,
          pageSize: 10,
          total: 500,
      },
      listLoading: false,
      dataList: [],

        dateQuery: [],
        rdChecked: 'getThisWeek',
        spinningDate: false,
        date: {
            start: '',
            end: '',
            time: 'getThisWeek'
        }
    };
  },
  filters: {
      formatLentime(val) {
         return formatLentime(val, '{y}-{m}-{d}')
      }
  },
  methods: {
      handleDatePickerChange(value, mode) {
          this.dateQuery = mode;
      },
      //时间框的弹出筛选
      openChange(status) {
          this.$nextTick(() => {
              if (!status) {
                  this.spinningDate = true;
                  setTimeout(() => {
                      this.spinningDate = false;
                      this.date.time = this.rdChecked;
                      this.date.start = this.dateQuery[0];
                      this.date.end = this.dateQuery[1];
                      this.fetch(this.requestParams());
                  }, 500)
              }
          });
      },
      //时间单选按钮组点击
    handleCheckedChange() {
        // 实现显示日期筛选
        if (this.rdChecked !== 'getCustom' || this.rdChecked != 'getAll') {
            this.date.time = this.rdChecked;
            delete this.date.start;
            delete this.date.end;
            this.spinningDate = true;
            setTimeout(() => {
                this.spinningDate = false
            }, 500)
            this.fetch(this.requestParams())
        }
    },
    handleDownload(e, obj) {
        e.preventDefault();
        this.listLoading = true;
        getInvoice({id: obj.id, type: 0}).then(res => {
            //download3(res.data, "transactionhistory.pdf", "application/pdf")
            download2(res.data).then(res => {}).finally(() => { this.listLoading = false })
        }).finally(() => {
            this.listLoading = false
        })
    },
    //公用请求参数
    requestParams() {
        let params = {}
        if (this.transactionType != -1) {
            params.type = this.transactionType;
        }

        if (this.dateQuery.length > 1) {
            params.start = this.dateQuery[0]+ ' 00:00:00';
            params.end = this.dateQuery[1]+ ' 23:59:59';
        }
        params.time = this.date.time;
        params.page = this.pagination.current;
        params.results = this.pagination.pageSize;

        params = JSON.parse(JSON.stringify(params));
        return params
    },

    searchTransactions() {
        this.fetch(this.requestParams())
    },

    //table 表单拉取数据
    fetch (params = {results: 5,page: 1}) {
        //查询前开始动画
        this.listLoading = true;
        getRecharge(params).then(res => {
            let { code, data } = res.data || {};
            if (code == 200) {
                this.dataList = data.records || [];
                this.pagination.total = data.total
            }
            this.listLoading = false;
        }).catch(e =>{
            console.log(e);
            this.listLoading = false;
        });
    },

    //监听分页的变化
    onShowSizeChange (page, pageSize) {
        console.log(page, pageSize);
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.fetch(this.requestParams())
    },
  },
  computed: {
    // 用户需自定义日期期限时，DatePicker的默认值
    datePickerDefaultValue() {
      const firstdate = this.$moment().subtract(7, 'days')
      const firstday = firstdate.hours(0).minutes(0).seconds(0).milliseconds(0)
      const lastday = this.$moment().endOf('day')
      return [firstday,lastday]
    },
    transactionTypes() {
        return this.$t('pro.admin.transactionTypes')
    },
    getTransactionIDMethods(){
        return this.$t('pro.AddTransactionID.methods')
    },
    status() {
        return this.$t('pro.admin.status')
    },
    columns() {
        let arry =  this.$t('pro.transactionRecord.columns');
        return arry.map(item => {
            let obj = {}
            if(item.dataIndex !== 'userId') {
                obj = item
            }
            return obj
        });
    },
    radios() { return new Map(this.$t('pro.public.radiosDate')) },
  },

  created() {
    this.fetch()
  }
};
</script>

<style lang="less">
.inline {
  display: flex;
  > div {
    margin-bottom: 0;
    margin-right: 15px;
  }
}
@media screen and (max-width: 768px){
  .inline {
    display: block;
    >div {
      margin-right: 0;
    }
  }
  .add-btn .ant-form-item-label {
    line-height: 0;
  }
}
</style>
